﻿using System;
using System.Linq;
using System.Web.Mvc;
using Inscriptionem.Authorization;
using Inscriptionem.Controllers.Base;
using Inscriptionem.Extensions;
using Inscriptionem.Models.Enums;
using Inscriptionem.Models.Requests;
using Inscriptionem.Models.Views;

namespace Inscriptionem.Controllers
{
    public class ContactController : BaseController
    {
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public ActionResult Index(ContactRequestModel model)
        {
            var result = new ContactViewModel();
            model.CopyTo(result);
            if (string.IsNullOrWhiteSpace(model.Mail) && Member.Current.ID != 0)
            {
                try
                {
                    var db = new ORM.DB();
                    result.Mail = db.Members.First(m => m.ID == Member.Current.ID).Mail;
                }
                catch (Exception) { }
            }

            if (Request.HttpMethod.ToLower() == "post")
            {
                // Checks
                if (string.IsNullOrWhiteSpace(result.Mail))
                {
                    result.Error = ContactError.MailEmpty;
                }
                else if (string.IsNullOrWhiteSpace(result.Message))
                {
                    result.Error = ContactError.MessageEmpty;
                }
                else if (!result.Mail.Contains("@"))
                {
                    result.Error = ContactError.MailNotValid;
                }
                else
                {
                    try
                    {
                        var db = new ORM.DB();
                        var request = new ORM.ContactRequest()
                                          {
                                              Mail = result.Mail,
                                              Message = result.Message,
                                              IsDeleted = false,
                                              CreatedDate = DateTime.Now,
                                              ModifiedDate = DateTime.Now
                                          };

                        if (Member.Current.ID != 0)
                        {
                            request.Member = db.Members.First(m => m.ID == Member.Current.ID);
                        }

                        db.AddToContactRequests(request);
                        db.SaveChanges();

                        // Success
                        return View("Success", result);
                    }
                    catch (Exception)
                    {
                        result.Error = ContactError.Other;
                    }
                }
            }

            return View(result);
        }

    }
}
